package com.example.dnfgamercommunitybackend.util;

import cn.hutool.dfa.WordTree;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class DfaUtil {
    private final WordTree wordTree = new WordTree();
    public DfaUtil() throws IOException {
        String filePath = "src/main/resources/keyWords/min_word.txt";
        List<String> keyWords = createKeyWordList(loadKeyWords(filePath));
        wordTree.addWords(keyWords);
    }

    public boolean textFilter(String text){
        List<String> filterResult = wordTree.matchAll(text,-1,false,false);
        return filterResult.isEmpty();
    }

    private List<String> createKeyWordList(String keyWord){
        //将字符串转换为List
        return Arrays
                .stream(keyWord.split("，"))
                .collect(Collectors.toList());
    }

    private String loadKeyWords(String path) throws IOException {
        StringBuilder stringBuffer = new StringBuilder();
        //读取关键词文件
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        String keyWords = null;
        //将文件转换为字符串
        while(StringUtils.hasText(keyWords = bufferedReader.readLine())){
            stringBuffer.append(keyWords.trim());
        }
        return stringBuffer.toString();
    }
}
